package net.cloudsun.graph.puzzle.group;

import net.cloudsun.graph.puzzle.JigsawState;

import java.io.*;
import java.util.Set;

/**
 * 存储群
 * created at 23/11/2021
 *
 * @author 俞建波
 * <a href="mailto://yujianbo@chtwm.com">yujianbo@chtwm.com</a>
 * @since 1.1.-
 */
public class VerticalRollGroupStore {

    public static void store(String originalDataFilePath, int centerNumber) throws IOException {
        final FileInputStream file = new FileInputStream(originalDataFilePath);
        final Set<PuzzleVerticalRollGroup> groups = new PuzzleVerticalRollGroupBuilder(centerNumber).build(file);
        // 一个文件存所有群
        final String dirPath = "vertical-roll-groups/" + centerNumber + "/";
        final File dir = new File(dirPath);
        if (!dir.exists() && !dir.mkdirs()) {
            return;
        }
        final File dataFile = new File(dirPath + centerNumber + ".data");
        if (!dataFile.exists() && !dataFile.createNewFile()) {
            return;
        }
        try (final PrintStream stream = new PrintStream(dataFile, "UTF-8")) {
            for (PuzzleVerticalRollGroup group : groups) {
                save(group, stream);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private static void save(PuzzleVerticalRollGroup group, PrintStream stream) throws IOException {
        // 存入文件中
        for (JigsawState state : group.getElements()) {
            stream.print(state.toSingleLineString());
            stream.print(" ");
        }
        stream.println();

    }
}
